﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace QDT.Web.KeyAlogrithm
{
    //C# RSA加密解密及RSA签名和验证
    /// <summary> 
    /// RSA加密解密及RSA签名和验证
    /// </summary> 
    public class RSAUtilSecurity
    {

        // 这个公钥由翰鑫科技平台产生，但是要经过转换为C#格式的密钥
        private const string publickey = @"<RSAKeyValue><Modulus>yVEpmkrO5uO+MbMVBnr3s4OunRo6fg5sR+ftMWsYh+mkODfadxQ+Bqoe6X7f/HwyEwiAak2VrFD3UmsSy08WBQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        // 这个私钥由翰鑫科技平台产生，但是要经过转换为C#格式的密钥，但是与公钥不一致，因为他们的接口没有提供解密的私钥
        private const string privatekey = @"<RSAKeyValue><Modulus>hfxmGNRxzPsArJsTAdxYsEzf1bfnrufv3D8LXCPEo9GayM0ujrbFFqMsqk8V+TNlRrQfmKzmjOHihWcC1daqLQ==</Modulus><Exponent>AQAB</Exponent><P>zLmwPEwgEnW+dJQYoWxMyiPGw9ZvEIz/dxR5QGo7+vc=</P><Q>p4siJbFQ4Nup6Yt1srOKvJAlFXsyPYHI6WmfJtlEtvs=</Q><DP>NwNzC1D9kVhYnKUrVT1wCSXCBOA7qjvpbktvJdMmWRM=</DP><DQ>UGnwDsVHO1VS/PvplsajvRM2KVRC7dB//L+sGnpHh8c=</DQ><InverseQ>lwPehea1zd/OMPE6GoZEyjv35ewh5EKnRODht7Z/ufo=</InverseQ><D>Pds4h14M68U1mno9XC6OA1Z6QACXRXhulA/G/tLEhZwjK+stZiQFpDhyAjzbQa3YI4uyZjpEPHMqRJVV3UkzQQ==</D></RSAKeyValue>";
        private static RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

        public byte[] RSAEncryptByte(string content)
        {
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            return cipherbytes;
        }
        public string RSAEncrypt(string content)
        {

            /*
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            return Convert.ToBase64String(cipherbytes);
            */
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            return Convert.ToBase64String(cipherbytes);
        }
        /// <summary>   
        /// RSA decrypt   
        /// </summary>   
        /// <param name="privatekey"></param>   
        /// <param name="content"></param>   
        /// <returns></returns>   
        public string RSADecrypt(byte[] content)
        {
            byte[] cipherbytes;
            rsa.FromXmlString(privatekey);
            cipherbytes = rsa.Decrypt(content, false);
            return Encoding.UTF8.GetString(cipherbytes);
        }

    }
}
